#!/usr/bin/env python
#
# Copyright 2009 Bret Taylor
#
# Licensed under the Apache License, Version 2.0 (the "License"); you may
# not use this file except in compliance with the License. You may obtain
# a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
# WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
# License for the specific language governing permissions and limitations
# under the License.

import optparse
import logging
import parser
import sys


def main():
    options, args = configure()
    if not args: sys.exit(1)

    files = []
    paths = sorted(set(args))
    for path in paths:
        ast = parser.parse(path, open(path).read().decode("utf-8"))
        if ast: files.append(ast)
    if len(files) != len(paths):
        sys.exit(1)
    if options.ast:
        parser.print_ast(ast)
        return


def configure():
    parser = optparse.OptionParser(
        usage="Usage: %prog [options] file0.dr file1.dr...")
    parser.add_option("--ast", action="store_true",
                      help="print the AST of the input files and exit")
    parser.add_option("--logging", default="info", metavar="LEVEL",
                      help="set the message log level (info, warning, error)")
    parser.add_option("--quiet", action="store_true",
                      help="disable all log messages")
    options, args = parser.parse_args()

    console = logging.StreamHandler()
    console.setFormatter(logging.Formatter("%(levelname)s: %(message)s"))
    logger = logging.getLogger(None)
    if options.quiet:
        logger.setLevel(logging.CRITICAL)
    else:
        try:
            logger.setLevel(getattr(logging, options.logging.upper()))
        except:
            logger.setLevel(logging.INFO)
    logger.addHandler(console)    

    return options, args


if __name__ == "__main__":
    main()
